import React, { useEffect, useRef, useState } from 'react';
import { Button, Input, Form, message } from 'antd';
import request from '@/utils/request';
import CateComp from '@/components/CategoryComponent';
import { useIntl, FormattedMessage } from 'umi';

const apiURL = '/api/services/app/Warehse/';
const WarehseEntry: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, []);

  const onFinish = (values: any) => {
    var model = values.model;
    model.id = props.id;
    setLoading(true);
    var act = 'Modify';
    if (model.id == 0 || !model.id) {
      act = 'New';
    }
    model.zip = '0';
    model.city = '0';
    model.state = '0';
    model.faxNum = '0';
    model.address = '0';
    model.country = '0';
    model.phoneNum = '0';
    request(apiURL + act, {
      method: 'POST',
      data: model,
    }).then((response) => {
      if (response) {
        if (response.success) {
          if (response.result.success) {
            message.success(intl.formatMessage({ id: 'pages.saveSuccess' }));
            props.fetchData();
          } else {
            message.error(response.result.message);
          }
        }
        setLoading(false);
      }
    });
  };

  const fetchDatas = () => {
    const { id } = props;
    if (id > 0) {
      request(apiURL + 'Get', {
        method: 'GET',
        params: { Id: id },
      }).then((response) => {
        var model = response?.result;
        formRef.current.setFieldsValue({ model });
      });
    }
  };

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  return (
    <Form {...layout} ref={formRef} onFinish={onFinish}>
      <Form.Item
        name={['model', 'warehouseCode']}
        label={<FormattedMessage id="pages.warehouseCode" />}
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.warehouseCode.required' }) }]}>
        <Input />
      </Form.Item>
      <Form.Item
        name={['model', 'description']}
        label={<FormattedMessage id="pages.warehouseDesc" />}
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.warehouseDesc.required' }) }]}>
        <Input />
      </Form.Item>
      <CateComp
        layout="warehouseType"
        width={200}
        name={['model', 'warehouseType']}
        label={<FormattedMessage id="pages.warehouseType" />}
        required
        rules={[{ required: true, message: intl.formatMessage({ id: 'pages.warehouseType.required' }) }]}
      />
      <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
        <Button type="primary" htmlType="submit" loading={loading}>
          <FormattedMessage id="pages.save" />
        </Button>
      </Form.Item>
    </Form>
  );
};

export default WarehseEntry;
